#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << " server-ip server-port" << std::endl;
        exit(0);
    }
    uint16_t server_port = std::stoi(argv[2]);
    std::string server_ip = argv[1];

    // 1.创建套接字
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "client socket create error!" << std::endl;
        exit(1);
    }

    // 2.给服务端发消息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);

    std::string line;
    while (1)
    {
        std::cout << "Please Enter# " ;
        std::getline(std::cin, line);
        int m = ::sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, len);
        if (m > 0)
        {
            //std::cout << "client sendto success!" << std::endl;
            // 3.接收服务端返回的信息
            char buffer[1024];
            struct sockaddr_in tmp;
            memset(&tmp, 0, sizeof(tmp));
            socklen_t len2 = sizeof(tmp);
            int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &len2);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "[服务端返回的信息]# " << buffer << std::endl;
            }
            else
            {
                std::cout << "client recvfrom error!" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "client sendto error!" << std::endl;
            break;
        }
    }

    return 0;
}